<!--
 * @Description: 
 * @Version: 1.0
 * @Autor: chen_yt
 * @Date: 2022-07-13 13:56:35
 * @LastEditors: chen_yt
 * @LastEditTime: 2022-08-10 10:53:02
-->
<template>
  <fks-drawer
    :visible.sync="Visible"
    direction="rtl"
    :before-close="close"
    custom-class="tenant-drawer"
    :show-close="false"
    :with-header="false"
    size="656px"
    destroy-on-close
  >
    <div
      v-loading="loading"
      class="tenant-drawer-container"
    >
      <div class="tenant-drawer-header">
        <template v-if="type == 'edit'">
          <i class="fks-icon-edit" />{{ LANG.EDIT_TENANT_MESSAGE }}
        </template>
        <template v-else>
          <i class="fks-icon-view" />{{ LANG.VIEW_TENANT_MESSAGE }}
        </template>
      </div>
      <div class="tenant-drawer-body">
        <!-- 放个form -->
        <fks-form
          ref="form"
          :model="form"
          :rules="rules"
        >
          <div class="form-divider-title">
            <i class="fks-icon-text" />
            {{ LANG.BASIC_MESSAGE }}
          </div>
          <fks-form-item
            :span="24"
            label="ID"
            prop="tenant.tenantId"
          >
            <fks-input
              v-model="form.tenant.tenantId"
              disabled
            />
          </fks-form-item>
          <fks-form-item
            :span="24"
            prop="tenant.tenantName"
            :label="LANG.TENANT_NAME"
          >
            <fks-input
              v-model="form.tenant.tenantName"
              maxlength="50"
              show-word-limit
            />
          </fks-form-item>
          <fks-form-item
            :label="LANG.REMARK"
            prop="remark"
          >
            <fks-input
              v-model="form.client.remark"
              type="textarea"
              maxlength="250"
              show-word-limit
              :autosize="{ minRows: 4, maxRows: 6 }"
            />
          </fks-form-item>

          <div class="form-divider-title">
            <i class="fks-icon-data-permission" />
            {{ LANG.MASTER_DATA_SETTING }}
          </div>
          <fks-form-item
            :label="LANG.MASTER_DATA"
            prop="dataMode"
          >
            <fks-checkbox-group v-model="form.dataMode">
              <fks-checkbox
                v-for="item in dataModeList"
                :key="item.label"
                disabled
                :label="item.label"
              >
                {{ item.name }}
              </fks-checkbox>
            </fks-checkbox-group>
            <div class="item-sp-tip">
              {{ LANG.MASTER_DATA_TIP }}
            </div>
          </fks-form-item>

          <div class="form-divider-title">
            <i class="fks-icon-department" />
            {{ LANG.PORTAL_MODE }}
          </div>
          <fks-form-item
            :label="LANG.MULITI_PORTAL_MODE"
            prop="multiPortal"
          >
            <fks-switch
              v-model="form.multiPortal"
              disabled
            />
            <div
              class="item-sp-tip"
              style="margin-top: 8px"
            >
              {{ LANG.MULITI_PORTAL_TIP }}
            </div>
          </fks-form-item>
        </fks-form>
      </div>
      <div
        v-if="type == 'edit'"
        class="tenant-drawer-footer"
      >
        <div class="operation-manual">
          <fks-button
            text
            icon="fks-icon-content"
            @click="openTenantNoteBook"
          >
            {{ LANG.OPERATION_MANUAL }}
          </fks-button>
        </div>
        <div class="button-container">
          <fks-button
            icon="fks-icon-close"
            :loading="submitLoading"
            @click="close"
          >
            {{ LANG.CANCEL }}
          </fks-button>
          <fks-button
            type="primary"
            icon="fks-icon-check"
            :loading="submitLoading"
            @click="submit"
          >
            {{ LANG.SAVE }}
          </fks-button>
        </div>
      </div>
    </div>
  </fks-drawer>
</template>

<script>
import { getTenant, getClient } from './api'
import { editTenant, saveClient } from '../api'
import { deepClone } from '@/utils/util'
import { DATA_MODE_TYPE, MASTER_DATA_TYPE } from '@/config/enums'
import deepmerge from 'deepmerge'
import {
  matchFormatToTimestamp,
  matchTimestampToFormat
} from '@/utils/timezone'

export default {
  name: 'TenantEdit',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    tenantIdInDataBase: {
      type: String,
      default: ''
    },
    clientIdInDataBase: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'edit'
    }
  },
  data() {
    return {
      Visible: false,
      loading: false,
      submitLoading: false,
      originTenant: {},
      originClient: {},
      form: {
        tenant: {},
        client: {},
        dataMode: [],
        multiPortal: false
      },
      oringinDataMode: [],
      oringinMultiPortal: false
    }
  },
  computed: {
    dataModeList() {
      return [
        { label: MASTER_DATA_TYPE.USER, name: this.LANG.USER_DATA },
        { label: MASTER_DATA_TYPE.ORG, name: this.LANG.ORG_DATA },
        { label: MASTER_DATA_TYPE.DIC, name: this.LANG.DIC_DATA }
      ]
    },
    //验证规则
    rules() {
      return {
        'tenant.tenantName': [
          {
            required: true,
            trigger: 'change'
          }
        ],
        'client.clientName': [
          {
            required: true,
            message: this.LANG.CLIENT_NAME_NOT_EMPTY,
            trigger: 'change'
          }
        ],
        'client.clientId': [
          {
            required: true,
            message: this.LANG.CLIENT_ID_RULE,
            trigger: 'change'
          }
        ],
        'client.clientSecret': [
          {
            required: true,
            message: this.LANG.CLIENT_SECRET_NOT_EMPTY,
            trigger: 'change'
          }
        ],
        'client.webServerRedirectUri': [
          {
            required: false,
            message: this.LANG.REDIRECT_URL_NOT_EMPTY,
            trigger: 'change'
          },
          {
            pattern: /^(https?):\/\/([\w-]+(\.[\w-]+)*\/?)+(([\w\-\.,@?^=%&:\/~\+#]*)+)?$/,
            message: this.LANG.REDIRECT_URL_PATTERN
          }
        ]
      }
    }
  },
  watch: {
    visible(val) {
      this.Visible = val
      if (val) {
        this.clearData()
        this.getTenantConfig()
      }
    },
    originTenant(val) {
      if (!val.id) {
        return
      }
      this.form.tenant = deepClone(this.originTenant)
    },
    originClient(val) {
      if (!val.id) {
        return
      }

      //client赋值
      let client = deepClone(this.originClient)

      if (!client.additionalInformation) {
        client.additionalInformation = {}
      } else {
        client.additionalInformation = JSON.parse(
          matchTimestampToFormat(client.additionalInformation)
        )
      }

      this.form.client = client

      //dataMode赋值
      let { dataMode } = client.additionalInformation

      let oringinDataMode = []

      if (typeof dataMode == 'object') {
        for (let key in dataMode) {
          if (dataMode[key] == DATA_MODE_TYPE.MASTER) {
            oringinDataMode.push(key)
          }
        }
      }

      this.oringinDataMode = oringinDataMode

      //MultiPortal赋值
      this.oringinMultiPortal =
        client.additionalInformation?.advancedConfig?.multiPortal ?? false
    },
    oringinDataMode(val) {
      this.form.dataMode = val
    },
    oringinMultiPortal(val) {
      this.form.multiPortal = val
    }
  },
  methods: {
    openTenantNoteBook() {
      window.open(' https://fawkes.cybereng.com/doc', '_blank')
    },
    getTenantConfig() {
      if (!this.tenantIdInDataBase || !this.clientIdInDataBase) {
        return
      }

      this.loading = true

      Promise.all([
        getTenant(this.tenantIdInDataBase),
        getClient(this.clientIdInDataBase)
      ])
        .then((res) => {
          if (res[0].status) {
            this.originTenant = res[0].data
          }
          if (res[1].status) {
            this.originClient = res[1].data
          }
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false
        })
    },

    submit() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        this.updateTenant()
      })
    },

    updateTenant() {
      let { client, tenant, multiPortal } = this.form

      let dataMode = {}

      this.dataModeList.forEach((item) => {
        dataMode[item.label] = this.form.dataMode.includes(item.label)
          ? DATA_MODE_TYPE.MASTER
          : DATA_MODE_TYPE.TENANT
      })

      let advancedConfig = { multiPortal }

      let additionalInformation = deepmerge(client.additionalInformation, {
        dataMode,
        advancedConfig
      })

      additionalInformation = JSON.parse(
        matchFormatToTimestamp(JSON.stringify(additionalInformation))
      )

      client.additionalInformation = additionalInformation

      this.submitLoading = true
      Promise.all([editTenant(tenant), saveClient(client)])
        .then((res) => {
          if (res[0].status && res[1].status) {
            this.$emit('onSave')
            this.close()
          }
        })
        .catch(() => {})
        .finally(() => {
          this.submitLoading = false
        })
    },

    clearData() {
      this.submitLoading = false
      this.originTenant = {}
      this.originClient = {}
      this.oringinDataMode = []
      this.oringinMultiPortal = false
      this.form = {
        tenant: {},
        client: {},
        dataMode: [],
        multiPortal: false
      }
      try {
        this.$refs.form.resetFields()
      } catch {}
    },

    close() {
      this.clearData()
      this.$emit('update:visible', false)
    }
  }
}
</script>


<style lang="scss" scoped>
.tenant-drawer {
  &-container {
    margin: 0;
    height: 100vh;
    position: relative;
    display: flex;
    flex-direction: column;
  }
  &-header {
    padding: 16px 16px;
    border-bottom: 1px #eeeeee solid;
    flex-shrink: 0;
    flex-grow: 0;

    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
    line-height: 22px;
    i {
      margin-right: 8px;
      font-size: 20px;
      color: var(--theme-color);
    }
  }
  &-body {
    flex-shrink: 1;
    flex-grow: 1;
    overflow-y: auto;
    overflow-x: hidden;
    .fks-form {
      margin-right: 0px;
      margin-left: 0;
    }
    .fks-form-item {
      padding-right: 24px;
    }
    &::-webkit-scrollbar {
      display: none;
    }
    .form-divider-title {
      border-bottom: 1px #eeeeee solid;
      width: 100%;
      margin: 16px 24px;
      padding-bottom: 8px;
      font-size: 14px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333;
      line-height: 20px;
      display: flex;
      align-items: center;
      &:nth-of-type(1) {
        margin-top: 24px;
      }
      i {
        color: var(--theme-color);
        margin-right: 4px;
        margin-bottom: -1px;
        font-size: 16px;
        // color: var(--theme-color);
      }
    }
  }
  &-footer {
    flex-shrink: 0;
    flex-grow: 0;
    display: flex;
    justify-content: space-between;
    padding: 16px 24px;
    margin-top: 16px;
    border-top: 1px #ddd solid;
  }
}

.item-sp-tip {
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: #cccccc;
  line-height: 19px;
}
</style>